from datetime import datetime

from fastapi import APIRouter, Depends, Request, Form

from core.template import AdminTemplates
from lib.common import (
    domain_mail_host, get_admin_email, get_admin_email_name
)
from lib.dependency.dependencies import validate_token
from lib.mail import mailer

router = APIRouter()
templates = AdminTemplates()
templates.env.globals["domain_mail_host"] = domain_mail_host

SENDMAIL_MENU_KEY = "100300"


@router.get("/sendmail_test")
async def visit_search(request: Request):
    """
    邮件测试
    """
    request.session["menu_key"] = SENDMAIL_MENU_KEY
    login_member = request.state.login_member

    context = {
        "request": request,
        "from_email": get_admin_email(request),
        "to_email": getattr(login_member, "mb_email", "")
    }
    return templates.TemplateResponse("sendmail_test.html", context)


@router.post("/sendmail_test_result", dependencies=[Depends(validate_token)])
async def sendmail_test_result(
    request: Request,
    to_email: str = Form(..., alias="email"),
):
    """
    邮件测试运行
    """
    # ','可以分离并转换为基于列表, 创建一个只有一个元素的列表
    subject = "[邮件检查] 标题"
    body = f'<span style="font-size:9pt;">[邮件检查] 内容\
        <p>如果这看起来是正确的，发送邮件服务器没有问题.<p>\
        {datetime.now()}<p>您的电子邮件地址将无法返回.</span>'
    from_email = get_admin_email(request)
    from_name = get_admin_email_name(request)
    real_emails = to_email.split(',') if ',' in to_email else [to_email]
    for to_email in real_emails:
        mailer(from_email, to_email, subject, body, from_name)

    context = {
        "request": request,
        "real_emails": real_emails,
    }
    return templates.TemplateResponse("sendmail_test_result.html", context)
